package com.hax2max.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.TableRow.LayoutParams;

import com.hax2max.R;
import com.hax2max.control.DataHandler;
import com.hax2max.control.FriendStalkerException;
import com.hax2max.control.FriendStalkerException.IExternalClient;
import com.hax2max.model.ExternalData;
import com.hax2max.service.FootprintUpdater;

public class MenuViewController{

    public static final int START = 0;
    public static final int MENULOGIN = 1;
    public static final int LOGIN = 2;   
    public static final int FETCHPERMISSION = 3;
    public static final int ERRORDIALOG = 4;
    public static final int PROFILE = R.id.profile;
    public static final int MAP = R.id.map;
    public static final int LIST = R.id.list;
    public static final int SETTINGS = R.id.settings;
    public static final int LOGOUT = R.id.logOut;
    public static final int UPDATE = R.id.menuUpdateStatus;

    private static MenuViewController instance;
    public DataHandler dataHandler;    
    private Context mContext;
    private Intent svc;
    private Dialog dialog;
    private Activity dialogActivity;
    private EditText statusUpdate;
    private TextView statusTextView;
    private ToggleButton toggleButtonFriendStalker;
    private ToggleButton toggleButtonFacebook;
    private ToggleButton toggleButtonTwitter;
    private Button statusButton;
    private OnClickListener onClickListener;
    private TextWatcher textWatcher;

    /**
     * simple check for login
     * @return true if the class has an instance
     */
    public static boolean isInstance() {
	if (instance == null)
	    return false;
	return true;
    }
    /**
     * Singleton Constructor
     * @param context
     * @return
     */
    public static MenuViewController getInstance(Context context){
	if (instance == null) 
	    instance = new MenuViewController(context);
	return instance;
    }

    /**
     * Checks if the logged in user is valid, will throw some wierd logmessage if datahandler didn't exist
     * @return true if user is valid
     */
    public boolean checkValidUser() {
	if (dataHandler == null) {
	    Log.e("MenuViewController","SHOULD NOT OCCUR! dataHandler was null, WHAHHHH");
	    dataHandler = new DataHandler(mContext);
	}
	if (!dataHandler.isLoggedIn())
	    return false;
	else return true; 
    }

    /**
     * The main login method, cover for dataHandler.
     * @param username
     * @param password
     * @return true | false
     * @throws FriendStalkerException
     */
    public boolean login(String username,String password) throws FriendStalkerException{
	dataHandler.loginUser(username, password);
	startService();
	return dataHandler.isLoggedIn();
    }

    /**
     * starts an activity
     */
    public boolean start(Object a, MenuItem item){
	if (item != null)
	    return start(a,item.getItemId());
	return false;
    }

    /**
     * starts an activity
     * @param a
     * @param id
     * @return
     */
    public boolean start(Object a, int id) {
	return start(a,id,new Bundle());
    }

    /**
     * starts a new activity
     * @param a an activity to spawn the next activity from
     * @param id what kind of item we are launching
     * @param b some extra data we want to send
     * @return
     */
    public boolean start(Object a, int id, Bundle b) {
	checkValidUser();
	if (a instanceof Activity){
	    Activity activity = (Activity)a;
	    mContext = activity.getBaseContext();
	    if (id == LOGOUT){
		stopService();
		dataHandler.logout();
	    }
	    Object o = getAction(id,activity.getBaseContext());
	    if (o instanceof Intent){
//		Log.e("MenuViewController","Robban: "+ ((Intent)o).toURI());
		if (!b.isEmpty()){
		    ((Intent)o).putExtras(b);
		}
		activity.startActivity((Intent)o);
	    }
	    else if (o instanceof String){
		String s = (String)o;
		if (s=="status"){
		    updateStatusDialog(activity);
		    dialog.show();
		} else if (s=="error"){
		    createDialog(activity,"Error",b.getInt("errorMessage")).show();
		}
	    }
	    return true;
	}
	return false;
    }
    /*****************************************************************************************
     * Private functions
     *****************************************************************************************/    
    private MenuViewController(Context context){
	mContext = context;
	initialize();
    }


    private void initialize() {

	Log.e("MenuViewController","ran initialize");
	if (dataHandler == null)
	    dataHandler = new DataHandler(mContext);
    }
    private void startService() {
	if (svc == null){
	    svc = new Intent(mContext, FootprintUpdater.class);
	    FootprintUpdater.setApp(dataHandler);
	    mContext.startService(svc);
	}
    }
    private void stopService() {
	mContext.stopService(svc);
    }

    private Dialog createDialog(Activity parent,String title,int message){
	Log.v("MenuViewController","dialog was null, init");
	AlertDialog newDialog = new AlertDialog.Builder(parent).setMessage(message).setTitle(title).create();
	newDialog.setCanceledOnTouchOutside(true);
	return newDialog;
    }

    private Dialog createDialog(Activity parent,String title,String message){
	Log.v("MenuViewController","dialog was null, init");
	AlertDialog newDialog = new AlertDialog.Builder(parent).setMessage(message).setTitle(title).create();
	newDialog.setCanceledOnTouchOutside(true);
	return newDialog;
    }

    private Object getAction(int pos,Context c){
	//R.id.profile,R.id.map,R.id.list,R.id.settings,R.id.logOut,R.id.menuUpdateStatus
	switch(pos){
	case PROFILE:return new Intent(TabHostController.actions[0],null,c,TabHostController.class);   //profile
	case MAP:Intent i = new Intent(c,MapViewController.class);
	return i;
//	i.addFlags(Intent.)
	case LIST:return new Intent(c,ListViewController.class); //Listview
	case SETTINGS:return new Intent(TabHostController.actions[3],null,c,TabHostController.class); //settings
	case LOGOUT:return new Intent(c,LoginViewController.class); //logout
	case UPDATE:return "status";
	case ERRORDIALOG: return "error";
	case FETCHPERMISSION: Log.e("MenuViewController", "Fetchpermission intent"); return new Intent(c,FacebookWebView.class);
	default: return null;
	}
    }

    private void updateStatusDialog(Activity parent){
	if (onClickListener == null)
	    onClickListener = new OnClickListener() {
	    @Override public void onClick(View v) {
		String s = statusUpdate.getText().toString();
		String facebookMessage = new String();
		String twitterMessage = new String();
		String stalkerMessage = new String();

		if (toggleButtonFacebook.isChecked()){
		    try {
			if( dataHandler.sendStatus(ExternalData.ApplicationIDFacebook, s) ) 
			    facebookMessage = "Updated facebook.";
			else facebookMessage = "Failed to update facebook.";
		    } catch (IExternalClient e) {
			facebookMessage = "Failed to update facebook. E = "+mContext.getResources().getString(e.errorMsgId);
		    }    
		}
		if(toggleButtonFriendStalker.isChecked()){
		    try {
			if (dataHandler.sendStatus(ExternalData.ApplicationIDFriendStalker, s))
			    stalkerMessage = "Updated friendstalker.";
			else stalkerMessage = "Failed to update friendstalker.";
		    } catch (IExternalClient e) {
			stalkerMessage = "Failed to update friendstalker. E = "+mContext.getResources().getString(e.errorMsgId);
		    }
		}
		if (toggleButtonTwitter.isChecked()){
		    try {
			if (dataHandler.sendStatus(ExternalData.ApplicationIDTwitter, s))
			    twitterMessage = "Updated twitter.";
			else twitterMessage = "Failed to update twitter.";
		    } catch (IExternalClient e) {
			twitterMessage = "Failed to update twitter. E = "+mContext.getResources().getString(e.errorMsgId);
		    }
		}
		Dialog d = createDialog(dialogActivity, "Status", facebookMessage + " " + twitterMessage + " " + stalkerMessage);
		d.show();
	    }
	};
	if (textWatcher == null)
	    textWatcher = new  TextWatcher() {
	    @Override public void afterTextChanged(Editable s) {}
	    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
	    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
		int letters = start+before;
		if (letters<=255){
		    toggleButtonFacebook.setTextOn("Facebook");
		}
		if (letters>140){toggleButtonTwitter.setTextOn("Chopped");
		if (toggleButtonTwitter.isChecked()){toggleButtonTwitter.setChecked(false);toggleButtonTwitter.setChecked(true);}
		}
		if (letters>255){toggleButtonFacebook.setTextOn("Chopped");
		if (toggleButtonFacebook.isChecked()){toggleButtonFacebook.setChecked(false);toggleButtonFacebook.setChecked(true);}
		}
		if (letters<=140){
		    toggleButtonTwitter.setTextOn("Twitter");
		}
		statusTextView.setText(""+letters);
	    }
	};
	Log.v("MenuViewController","dialog was null, init");
	dialogActivity = parent;
	dialog = new Dialog(parent);
	dialog.setTitle("Update your status");
	dialog.setCanceledOnTouchOutside(true);
	dialog.setContentView(R.layout.menu_update_status);    
	statusButton = (Button)dialog.findViewById(R.id.menuUpdateButton);
	statusTextView = (TextView)dialog.findViewById(R.id.menuUpdateStatusTextView);
	statusUpdate = (EditText)dialog.findViewById(R.id.menuUpdateStatusEditText);
	toggleButtonFacebook = (ToggleButton)dialog.findViewById(R.id.menuUpdateFacebook);
	toggleButtonTwitter = (ToggleButton)dialog.findViewById(R.id.menuUpdateTwitter);
	toggleButtonFriendStalker = (ToggleButton)dialog.findViewById(R.id.menuUpdateFriendStalker);
	statusUpdate.addTextChangedListener( textWatcher );
	statusButton.setOnClickListener( onClickListener );
	statusUpdate.setSingleLine();
    }
}